﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;

namespace System.Peppers.Win32
{
    public static class Shutdown
    {
        [DllImport("advapi32.dll", SetLastError = true)]
        private extern static bool InitiateSystemShutdown(string machineName, string message, int timeout, bool forceClosed, bool reboot);

        [DllImport("advapi32.dll", SetLastError = true)]
        private extern static bool AbortSystemShutdown(string machineName);

        /// <summary>
        /// Shuts down the local computer with a default timeout of 30 seconds
        /// </summary>
        public static void Initiate()
        {
            Initiate(new ShutdownParameters { Timeout = 30 });
        }

        /// <summary>
        /// Shuts down with parameters
        /// </summary>
        /// <param name="parameters">parameters to InitiateSystemShutdown</param>
        public static void Initiate(ShutdownParameters parameters)
        {
            if (!InitiateSystemShutdown(parameters.MachineName, parameters.Message, parameters.Timeout, parameters.ForceCloseApps, parameters.Restart))
            {
                throw new Win32Exception();
            }
        }

        /// <summary>
        /// Aborts a shutdown on the local system
        /// </summary>
        public static void Abort()
        {
            Abort(null);
        }

        /// <summary>
        /// Aborts a shutdown with specified computer name
        /// </summary>
        /// <param name="machineName">Computer to shutdown</param>
        public static void Abort(string machineName)
        {
            if (!AbortSystemShutdown(machineName))
            {
                throw new Win32Exception();
            }
        }
    }
}
